<!doctype html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-demo="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .router-link-active {
            color:#f00;
        }
        pre {
            font-family: sans-serif;
            font-size: 1em;
            line-height:1.5em;
        }

    </style>
</head>
<body>

    <div id="app">
        <ul>
            <li><router-link to="/">Home</router-link></li>
            <li><router-link to="/post">Post</router-link></li>
        </ul>
        <router-view></router-view>
    </div>
</body>

<script src="../../../vender/vue@2.4.2.js"></script>
<script src="../../../vender/vue-router@2.7.0.js"></script>

<script>
    const Home={template:'<div><h2>Home</h2></div>'};

    const Post={template:`<div>
            <h2>Post:</h2>
            <div class="loading" v-if="loading">Loading...</div>
            <div class="error" v-if="error">{{error}}</div>
            <div class="post" v-if="post">
                <h3>{{post.title}}</h3>
                <div>{{post.body}}</div>
            </div>
        </div>`,
        data(){
            return {
                loading:false,
                error:null,
                post:null
            }
        },
        created(){
            console.log('created');
            this.fetch();
        },
        watch:{
          '$route':'fetch'
        },
        methods:{
            fetch(){
                this.error=this.post=null;
                this.loading=true;
                setTimeout(()=>{
                    this.loading=false;
                    if(Math.random()<0.3){
                        this.error='请求错误';
                    }else{
                        this.post={
                            title:'postTitle',
                            body:'postBody'
                        };
                        console.log('post:',this.post);
                    }
                },Math.random()*2000|0);
            }
        }
    };

    const router=new VueRouter({
        routes:[
            {path:'',component:Home},
            {
                path:'/post',component:Post
            }
        ]

    });

    const app=new Vue({
        el:'#app',
        router
    });

</script>
</html>